/**
 * Copyright 2020 Inc.
 **/
package com.myz.distributed.transaction.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author maoyz0621 on 2020/8/5
 * @version v1.0
 */
@Component
@Slf4j
public class MqProducer {

    /**
     * springboot提供
     */
    @Resource
    RocketMQTemplate rocketMQTemplate;
    /**
     * rocketmq-client提供
     */
    @Resource
    DefaultMQProducer defaultMQProducer;


    /**
     * 事务消息
     * 事务消息不支持延时消息和批量消息。
     */
    public void sendTransaction(String txProducerGroup, String topic, Object order, String rocketHeader, String rocketHeaderVal) {
        // In sendMessageInTransaction(), the first parameter transaction name ("test")
        // must be same with the @RocketMQTransactionListener's member field 'transName'
        TransactionSendResult transaction = rocketMQTemplate.sendMessageInTransaction(txProducerGroup,
                topic,
                MessageBuilder.withPayload(order).setHeader(rocketHeader, rocketHeaderVal).build(),
                "aaaa");
        LocalTransactionState localTransactionState = transaction.getLocalTransactionState();
        log.info("事务消息:msgId = {},send = {}, status = {}\r\n", transaction.getMsgId(), localTransactionState, transaction.getSendStatus());
    }

}